package com.infitecs.eyas.develop;

import com.infitecs.eyas.develop.model.Menu;
import com.infitecs.eyas.develop.service.I18NService;
import com.infitecs.eyas.develop.service.MenuService;
import com.infitecs.krill.ajax.response.AjaxResponse;
import com.infitecs.krill.ajax.response.ReturnState;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/develop/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @RequestMapping("/sidebar")
    public String showSidebar(Model model) {
        return "/develop/sidebar";
    }

    @RequestMapping("/current")
    public String getCurrent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Menu> menuMap = (HashMap) request.getServletContext().getAttribute("menuMap");
        Menu menu = menuMap.get(request.getParameter("menuId"));
        int level = Integer.parseInt(menu.getLevel());
        String current = "<li><span><i class='" + menu.getIcon() + "'></i>" + menu.getMenuName() + "<span></li>";
        for (int i = 0; i < level; i++) {
            menu = menuMap.get(menu.getParentId());
            current = "<li><span><i class='" + menu.getIcon() + "'></i> " + menu.getMenuName()
                    + "</span><i class='fa fa-angle-right'></i>" + current;
        }
        response.getWriter().write(current);
        return null;
    }

    @RequestMapping("/menuSearch")
    @ResponseBody
    public AjaxResponse menuSearch(String menuId, HttpServletRequest request) {
        Menu menu = menuService.getMenu(menuId);
        if (SecurityUtils.getSubject().isPermitted(menu.getPermToken())) {
            String url = menu.getUrl();
            url = url + (url.contains("?") ? "&" : "?") + "menuId=" + menu.getMenuId();
            return new AjaxResponse("url", url);
        } else {
            return new AjaxResponse(ReturnState.ERROR, I18NService.getResourceBundleString(request.getSession(), "permission.denied"));
        }
    }
}
